package com.lizicloud.infrastructure.common.utils;

import java.util.concurrent.*;
import java.util.function.Supplier;

/**
 * 线程工具类
 */
public class ThreadUtils {
    
    /**
     * 默认线程池
     */
    private static final ExecutorService DEFAULT_EXECUTOR = Executors.newCachedThreadPool();
    
    /**
     * 定时任务线程池
     */
    private static final ScheduledExecutorService SCHEDULED_EXECUTOR = Executors.newScheduledThreadPool(4);
    
    /**
     * 休眠指定的毫秒数
     */
    public static void sleep(long millis) {
        if (millis <= 0) {
            return;
        }
        
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    /**
     * 休眠指定的秒数
     */
    public static void sleepSeconds(int seconds) {
        sleep(seconds * 1000L);
    }
    
    /**
     * 获取当前线程名称
     */
    public static String getCurrentThreadName() {
        return Thread.currentThread().getName();
    }
    
    /**
     * 获取当前线程ID
     */
    public static long getCurrentThreadId() {
        return Thread.currentThread().getId();
    }
    
    /**
     * 检查当前线程是否被中断
     */
    public static boolean isInterrupted() {
        return Thread.currentThread().isInterrupted();
    }
    
    /**
     * 中断当前线程
     */
    public static void interrupt() {
        Thread.currentThread().interrupt();
    }
    
    /**
     * 创建新线程
     */
    public static Thread newThread(Runnable runnable, String name) {
        if (runnable == null) {
            return null;
        }
        
        Thread thread = new Thread(runnable);
        if (name != null && !name.isEmpty()) {
            thread.setName(name);
        }
        return thread;
    }
    
    /**
     * 异步执行任务
     */
    public static void executeAsync(Runnable task) {
        if (task == null) {
            return;
        }
        
        DEFAULT_EXECUTOR.execute(task);
    }
    
    /**
     * 异步执行任务并获取结果
     */
    public static <T> Future<T> executeAsync(Supplier<T> task) {
        if (task == null) {
            return null;
        }
        
        return DEFAULT_EXECUTOR.submit(task::get);
    }
    
    /**
     * 延迟执行任务
     */
    public static void schedule(Runnable task, long delayMillis) {
        if (task == null || delayMillis < 0) {
            return;
        }
        
        SCHEDULED_EXECUTOR.schedule(task, delayMillis, TimeUnit.MILLISECONDS);
    }
    
    /**
     * 定时执行任务
     */
    public static ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long initialDelay, long periodMillis) {
        if (task == null || periodMillis <= 0) {
            return null;
        }
        
        return SCHEDULED_EXECUTOR.scheduleAtFixedRate(task, initialDelay, periodMillis, TimeUnit.MILLISECONDS);
    }
    
    /**
     * 定时执行任务（固定延迟）
     */
    public static ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long initialDelay, long delayMillis) {
        if (task == null || delayMillis <= 0) {
            return null;
        }
        
        return SCHEDULED_EXECUTOR.scheduleWithFixedDelay(task, initialDelay, delayMillis, TimeUnit.MILLISECONDS);
    }
    
    /**
     * 等待线程结束
     */
    public static void waitFor(Thread thread) {
        if (thread == null) {
            return;
        }
        
        try {
            thread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    /**
     * 等待线程结束（指定超时时间）
     */
    public static boolean waitFor(Thread thread, long timeoutMillis) {
        if (thread == null) {
            return false;
        }
        
        try {
            thread.join(timeoutMillis);
            return !thread.isAlive();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }
    
    /**
     * 获取CPU核心数
     */
    public static int getCpuCores() {
        return Runtime.getRuntime().availableProcessors();
    }
    
    /**
     * 获取活跃线程数
     */
    public static int getActiveThreadCount() {
        return Thread.activeCount();
    }
    
    /**
     * 获取线程组
     */
    public static ThreadGroup getThreadGroup() {
        return Thread.currentThread().getThreadGroup();
    }
    
    /**
     * 关闭线程池
     */
    public static void shutdown() {
        DEFAULT_EXECUTOR.shutdown();
        SCHEDULED_EXECUTOR.shutdown();
        
        try {
            if (!DEFAULT_EXECUTOR.awaitTermination(5, TimeUnit.SECONDS)) {
                DEFAULT_EXECUTOR.shutdownNow();
            }
            if (!SCHEDULED_EXECUTOR.awaitTermination(5, TimeUnit.SECONDS)) {
                SCHEDULED_EXECUTOR.shutdownNow();
            }
        } catch (InterruptedException e) {
            DEFAULT_EXECUTOR.shutdownNow();
            SCHEDULED_EXECUTOR.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
    
    /**
     * 获取线程状态
     */
    public static Thread.State getThreadState(Thread thread) {
        if (thread == null) {
            return null;
        }
        return thread.getState();
    }
    
    /**
     * 检查线程是否存活
     */
    public static boolean isAlive(Thread thread) {
        if (thread == null) {
            return false;
        }
        return thread.isAlive();
    }
    
    /**
     * 设置线程优先级
     */
    public static void setPriority(Thread thread, int priority) {
        if (thread == null) {
            return;
        }
        
        if (priority >= Thread.MIN_PRIORITY && priority <= Thread.MAX_PRIORITY) {
            thread.setPriority(priority);
        }
    }
    
    /**
     * 获取线程优先级
     */
    public static int getPriority(Thread thread) {
        if (thread == null) {
            return Thread.NORM_PRIORITY;
        }
        return thread.getPriority();
    }
    
    /**
     * 设置线程名称
     */
    public static void setName(Thread thread, String name) {
        if (thread == null || name == null) {
            return;
        }
        thread.setName(name);
    }
    
    /**
     * 获取线程名称
     */
    public static String getName(Thread thread) {
        if (thread == null) {
            return "";
        }
        return thread.getName();
    }
    
    /**
     * 线程安全的单例模式
     */
    public static class ThreadSafeSingleton {
        private static volatile ThreadSafeSingleton instance;
        
        private ThreadSafeSingleton() {
            // 私有构造函数
        }
        
        public static ThreadSafeSingleton getInstance() {
            if (instance == null) {
                synchronized (ThreadSafeSingleton.class) {
                    if (instance == null) {
                        instance = new ThreadSafeSingleton();
                    }
                }
            }
            return instance;
        }
    }
    
    private ThreadUtils() {
        // 私有构造函数，防止实例化
    }
}